from flask_restful import Resource
from flask import g
from app.user.models import UserModel
from app.common.constants import ResultCode
from app.common.response import api_response
from app.ext import r
from app import user_app


class Insert(Resource):
    user = UserModel()

    def post(self):
        data = g.data
        result = self.user.insert(data)
        if result:
            response = api_response(result_code=ResultCode.INSERT, user_id=data['user_id'])
            user_app.logger.error({"message": 'insert- data:{} success'.format(data)})
        else:
            user_app.logger.error({"message": 'insert - data:{} existed'.format(data)})
            response = api_response(result_code=ResultCode.REGISTERED, user_id=data['user_id'])
        return response


class Delete(Resource):
    user = UserModel()

    def post(self):
        data = g.data
        result = self.user.delete(data)
        if result:
            response = api_response(result_code=ResultCode.DELETE, user_id=data['user_id'])
            user_app.logger.error({"message": 'detele - user_id:{} success'.format(data['user_id'])})
        else:
            response = api_response(result_code=ResultCode.NON_EXISTENT, user_id=data['user_id'])
            user_app.logger.error({"message": 'detele - user_id:{} does not exist'.format(data['user_id'])})
        return response


class Update(Resource):
    user = user = UserModel()

    def post(self):
        data = g.data
        result = self.user.update(data)
        if result:
            response = api_response(result_code=ResultCode.UPDATE, user_id=data['user_id'])
            user_app.logger.error({"message": 'update - user_id:{} success'.format(data['user_id'])})
        else:
            response = api_response(result_code=ResultCode.NON_EXISTENT, user_id=data['user_id'])
            user_app.logger.error({"message": 'update - user_id:{} does not exist'.format(data['user_id'])})
        return response


class UserInfo(Resource):
    user = user = UserModel()

    def get(self):
        user_id = g.user_id
        if r.get(user_id['user_id']):  # 判断redis 是否还存在user_id
            r.expire(user_id['user_id'], 300)
            result = self.user.user_info(user_id)
            response = api_response(result_code=ResultCode.INFO, content=result)
            user_app.logger.error({"message": 'user_info - user_id:{} success'.format(user_id)})
        else:
            response = api_response(result_code=ResultCode.TOKEN_EXPIRED)
            user_app.logger.error({"message": 'user_info - user_id:{} existed'.format(user_id)})
        return response

